<template>
  <div class="address-management">
    <!-- 顶部操作区域 -->
    <div class="address-header">
      <div class="address-count">
        <span class="count-text">共 {{ addressList.length }} 个收货地址</span>
        <span class="count-limit">（最多可添加5个）</span>
      </div>
      <el-button 
        type="primary" 
        @click="handleAddAddress"
        :disabled="addressList.length >= 5"
      >
        <span class="btn-icon">➕</span>
        新增收货地址
      </el-button>
    </div>

    <!-- 地址列表 -->
    <div class="address-list" v-loading="loading">
      <div v-if="addressList.length === 0" class="empty-state">
        <div class="empty-icon">📍</div>
        <p class="empty-text">暂无收货地址</p>
        <p class="empty-desc">请添加您的收货地址，方便订单配送</p>
        <el-button type="primary" @click="handleAddAddress">
          立即添加
        </el-button>
      </div>

      <div 
        v-for="address in addressList" 
        :key="address.id"
        class="address-item"
        :class="{ 'default-address': address.isDefault === 1 }"
      >
        <div class="address-content">
          <!-- 默认标签 -->
          <el-tag v-if="address.isDefault === 1" class="default-tag" type="success" size="small">
            默认
          </el-tag>
          
          <!-- 收货人信息 -->
          <div class="receiver-info">
            <span class="receiver-name">{{ address.receiverName }}</span>
            <span class="receiver-phone">{{ address.receiverPhone }}</span>
          </div>
          
          <!-- 详细地址 -->
          <div class="address-detail">
            {{ address.fullAddress }}
          </div>
          
          <!-- 邮政编码 -->
          <div v-if="address.postalCode" class="postal-code">
            邮编：{{ address.postalCode }}
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="address-actions">
          <el-button 
            v-if="address.isDefault !== 1"
            link 
            type="primary" 
            @click="handleSetDefault(address.id)"
          >
            设为默认
          </el-button>
          <el-button link type="primary" @click="handleEditAddress(address)">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDeleteAddress(address.id)">
            删除
          </el-button>
        </div>
      </div>
    </div>

    <!-- 新增/编辑地址弹窗 -->
    <el-dialog
      v-model="showAddressDialog"
      :title="isEdit ? '编辑收货地址' : '新增收货地址'"
      width="600px"
      :close-on-click-modal="false"
      class="address-dialog"
    >
      <el-form 
        ref="addressFormRef"
        :model="addressForm" 
        :rules="addressRules" 
        label-width="100px"
        class="address-form"
      >
        <el-form-item label="收货人" prop="receiverName">
          <el-input 
            v-model="addressForm.receiverName" 
            placeholder="请输入收货人姓名"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="手机号" prop="receiverPhone">
          <el-input 
            v-model="addressForm.receiverPhone" 
            placeholder="请输入手机号"
            maxlength="11"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="所在地区" required>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item prop="province">
                <el-input 
                  v-model="addressForm.province" 
                  placeholder="省份"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="city">
                <el-input 
                  v-model="addressForm.city" 
                  placeholder="城市"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="district">
                <el-input 
                  v-model="addressForm.district" 
                  placeholder="区县"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input 
            v-model="addressForm.detailedAddress" 
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址，如道路、门牌号、小区、楼栋号、单元等信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="邮政编码" prop="postalCode">
          <el-input 
            v-model="addressForm.postalCode" 
            placeholder="请输入邮政编码（选填）"
            maxlength="6"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="设为默认">
          <el-switch 
            v-model="addressForm.isDefault" 
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSaveAddress"
            :loading="saving"
          >
            确认保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getAddressList, 
  addAddress, 
  updateAddress, 
  deleteAddress, 
  setDefaultAddress 
} from '@/api/address'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const addressList = ref([])
const showAddressDialog = ref(false)
const isEdit = ref(false)
const currentEditId = ref(null)

// 地址表单
const addressFormRef = ref()
const addressForm = reactive({
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  detailedAddress: '',
  postalCode: '',
  isDefault: 0
})

// 表单验证规则
const addressRules = {
  receiverName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在2-20个字符之间', trigger: 'blur' }
  ],
  receiverPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请输入省份', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请输入城市', trigger: 'blur' }
  ],
  district: [
    { required: true, message: '请输入区县', trigger: 'blur' }
  ],
  detailedAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 200, message: '详细地址长度在5-200个字符之间', trigger: 'blur' }
  ],
  postalCode: [
    { pattern: /^\d{6}$/, message: '邮政编码格式不正确', trigger: 'blur' }
  ]
}

// 获取地址列表
const fetchAddressList = async () => {
  loading.value = true
  try {
    const response = await getAddressList()
    if (response.success) {
      addressList.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取地址列表失败')
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败')
  } finally {
    loading.value = false
  }
}

// 新增地址
const handleAddAddress = () => {
  if (addressList.value.length >= 5) {
    ElMessage.warning('收货地址最多只能添加5个')
    return
  }
  
  isEdit.value = false
  currentEditId.value = null
  resetForm()
  showAddressDialog.value = true
}

// 编辑地址
const handleEditAddress = (address) => {
  isEdit.value = true
  currentEditId.value = address.id
  
  // 填充表单数据
  addressForm.receiverName = address.receiverName
  addressForm.receiverPhone = address.receiverPhone
  addressForm.province = address.province
  addressForm.city = address.city
  addressForm.district = address.district
  addressForm.detailedAddress = address.detailedAddress
  addressForm.postalCode = address.postalCode || ''
  addressForm.isDefault = address.isDefault
  
  showAddressDialog.value = true
}

// 保存地址
const handleSaveAddress = async () => {
  try {
    await addressFormRef.value.validate()
    
    saving.value = true
    const data = {
      receiverName: addressForm.receiverName,
      receiverPhone: addressForm.receiverPhone,
      province: addressForm.province,
      city: addressForm.city,
      district: addressForm.district,
      detailedAddress: addressForm.detailedAddress,
      postalCode: addressForm.postalCode || null,
      isDefault: addressForm.isDefault
    }
    
    let response
    if (isEdit.value) {
      response = await updateAddress(currentEditId.value, data)
    } else {
      response = await addAddress(data)
    }
    
    if (response.success) {
      ElMessage.success(isEdit.value ? '更新地址成功' : '新增地址成功')
      handleCloseDialog()
      // 重新获取地址列表
      await fetchAddressList()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    if (error !== false) { // 过滤表单验证失败的错误
      console.error('保存地址失败:', error)
      ElMessage.error('保存地址失败')
    }
  } finally {
    saving.value = false
  }
}

// 删除地址
const handleDeleteAddress = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个收货地址吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteAddress(id)
    if (response.success) {
      ElMessage.success('删除地址成功')
      // 重新获取地址列表
      await fetchAddressList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除地址失败:', error)
      ElMessage.error('删除地址失败')
    }
  }
}

// 设置默认地址
const handleSetDefault = async (id) => {
  try {
    const response = await setDefaultAddress(id)
    if (response.success) {
      ElMessage.success('设置默认地址成功')
      // 重新获取地址列表
      await fetchAddressList()
    } else {
      ElMessage.error(response.message || '设置失败')
    }
  } catch (error) {
    console.error('设置默认地址失败:', error)
    ElMessage.error('设置默认地址失败')
  }
}

// 关闭弹窗
const handleCloseDialog = () => {
  showAddressDialog.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  addressForm.receiverName = ''
  addressForm.receiverPhone = ''
  addressForm.province = ''
  addressForm.city = ''
  addressForm.district = ''
  addressForm.detailedAddress = ''
  addressForm.postalCode = ''
  addressForm.isDefault = 0
  addressFormRef.value?.clearValidate()
}

// 初始化
onMounted(() => {
  fetchAddressList()
})
</script>

<style lang="scss" scoped>
.address-management {
  padding: 20px;
}

/* 顶部操作区域 */
.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.address-count {
  font-size: 14px;
  color: #606266;
}

.count-text {
  font-weight: 600;
  color: #303133;
}

.count-limit {
  color: #909399;
  margin-left: 8px;
}

.btn-icon {
  margin-right: 4px;
}

/* 地址列表 */
.address-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-text {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.empty-desc {
  font-size: 14px;
  color: #909399;
  margin-bottom: 24px;
}

/* 地址项 */
.address-item {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  border: 2px solid transparent;
  
  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }
  
  &.default-address {
    border-color: #67c23a;
    background: linear-gradient(135deg, #f0f9ff 0%, #ffffff 100%);
  }
}

.address-content {
  flex: 1;
  position: relative;
}

.default-tag {
  position: absolute;
  top: -5px;
  right: 0;
  font-weight: 600;
}

.receiver-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  gap: 16px;
}

.receiver-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.receiver-phone {
  font-size: 14px;
  color: #606266;
}

.address-detail {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  margin-bottom: 8px;
}

.postal-code {
  font-size: 13px;
  color: #909399;
}

.address-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-left: 20px;
}

/* 弹窗样式 */
.address-dialog {
  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
    color: white;
    padding: 20px 24px;
    margin: 0;
  }
  
  :deep(.el-dialog__title) {
    color: white;
    font-weight: 600;
  }
  
  :deep(.el-dialog__headerbtn .el-dialog__close) {
    color: white;
    font-size: 20px;
  }
  
  :deep(.el-dialog__body) {
    padding: 24px;
  }
  
  :deep(.el-dialog__footer) {
    padding: 16px 24px 24px;
  }
}

.address-form {
  :deep(.el-form-item) {
    margin-bottom: 20px;
  }
  
  :deep(.el-form-item__label) {
    color: #606266;
    font-weight: 600;
    font-size: 14px;
  }
  
  :deep(.el-input__wrapper) {
    border-radius: 8px;
    padding: 8px 15px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
    
    &:hover {
      box-shadow: 0 2px 6px rgba(64, 158, 255, 0.15);
    }
    
    &.is-focus {
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    }
  }
  
  :deep(.el-textarea__inner) {
    border-radius: 8px;
    padding: 10px 15px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
    
    &:hover {
      box-shadow: 0 2px 6px rgba(64, 158, 255, 0.15);
    }
    
    &:focus {
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .address-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .address-item {
    flex-direction: column;
  }
  
  .address-actions {
    flex-direction: row;
    margin-left: 0;
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #f0f0f0;
    width: 100%;
    justify-content: flex-end;
  }
  
  .address-dialog {
    :deep(.el-dialog) {
      width: 90%;
      margin: 0 auto;
    }
  }
}
</style>

